@echo off
chcp 65001 >nul
echo 🚀 Starting Molecule Scope Application (Complete Setup)...
echo.

echo 🔍 Checking if ports 8001 and 8002 are available...
echo.

REM Check port 8001
netstat -ano | findstr ":8001" >nul
if %errorlevel% equ 0 (
    echo ❌ Port 8001 is already in use!
    echo Please close any applications using port 8001 and try again.
    pause
    exit /b 1
) else (
    echo ✅ Port 8001 is available
)

REM Check port 8002  
netstat -ano | findstr ":8002" >nul
if %errorlevel% equ 0 (
    echo ❌ Port 8002 is already in use!
    echo Please close any applications using port 8002 and try again.
    pause
    exit /b 1
) else (
    echo ✅ Port 8002 is available
)

echo.
echo 📦 Installing Python dependencies...
pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
if %errorlevel% neq 0 (
    echo ❌ Failed to install Python dependencies
    pause
    exit /b 1
)

echo.
echo 📦 Installing Node.js dependencies...
cd client
npm install
if %errorlevel% neq 0 (
    echo ❌ Failed to install Node.js dependencies
    pause
    exit /b 1
)

echo.
echo 🎯 Starting Backend Server (Port 8001)...
start "Molecule Scope Backend" cmd /k "python ../main.py"

echo 🎯 Starting Frontend Server (Port 8002)...
start "Molecule Scope Frontend" cmd /k "npm run dev"

echo.
echo ⏳ Waiting for servers to start...
timeout /t 10 /nobreak >nul

echo.
echo 🔍 Testing backend health check...
powershell -Command "try { $response = Invoke-RestMethod -Uri 'http://localhost:8001/health' -Method Get -TimeoutSec 5; if ($response.status -eq 'healthy') { echo '✅ Backend server is running healthy!' } else { echo '❌ Backend server returned unexpected status' } } catch { echo '❌ Backend server is not responding' }"

echo.
echo 🌐 Application URLs:
echo Backend API:  http://localhost:8001
echo Frontend App: http://localhost:8002
echo.
echo 📋 Available API Endpoints:
echo   - GET  /health              - Health check
echo   - GET  /docs                - API documentation
echo   - POST /search/molecule     - Search molecules
echo   - GET  /molecule/{mp_id}    - Get molecule details
echo   - GET  /papers/{query}      - Get research papers
echo   - GET  /suppliers/{query}   - Get supplier information
echo.
echo 🎉 Setup complete! Both servers are running.
echo Press any key to exit this window (servers will continue running)...
pause >nul